module cfg_UART(RX_C, TX_C, clk, rst_n, rsp_data, clr_frm_rdy, snd_rsp, frm_rdy, cfg_data);

input RX_C, clk, rst_n, snd_rsp, clr_frm_rdy;
input [15:0] rsp_data;

output reg [23:0] cfg_data;
output reg frm_rdy;
output TX_C;



wire[7:0] rx_data, tx_data;

reg[7:0] cfg_upper, cfg_lower, cfg_crap;
reg [2:0] state, nxt_state;

wire tx_done, rdy;
logic trmt, clr_rdy;

UART u(tx_data, trmt ,tx_done ,clk, rst_n, TX_C, RX_C, rx_data, rdy, clr_rdy);



assign cfg_data = {cfg_upper, cfg_lower, cfg_crap};

always @(posedge clk, negedge rst_n)begin
	if(!rst_n)
		state <= 3'h0;
	else
		state <= nxt_state;
end


//transmit flop
reg [7:0] hold;
logic tx_byte;
always @(posedge clk)begin
	if(snd_rsp)
		hold <= rsp_data[15:8];
end	
assign tx_data = (tx_byte)? rsp_data[7:0]:hold;

//rx bytes
logic byte1, byte2, byte3;
always @(posedge clk)begin
	if(byte1)
		cfg_upper <= rx_data;
	if(byte2)
		cfg_lower <= rx_data;
	if(byte3)
		cfg_crap <= rx_data;
end

//frm_rdy logic
logic set_frm, rst_frm;
always @(posedge clk, negedge rst_n)begin
	if(!rst_n)
		frm_rdy <= 1'b0;
	else if(set_frm)
		frm_rdy <= 1'b1;
	else if(clr_frm_rdy)
		frm_rdy <= 1'b0;
end



always_comb begin
	
	nxt_state = 0;
	
	byte1 = 0;
	byte2 = 0;
	byte3 = 0;
	clr_rdy = 0;
	trmt = 0;
	tx_byte = 1;
	set_frm = 0;
	rst_frm = 0;
	
	case(state)
		3'b000:begin
			nxt_state = 3'b000;
			if(snd_rsp)begin
				nxt_state = 3'b001;
				tx_byte = 1;
				trmt = 1;
			end
			else if(rdy)begin
				byte1 = 1;
				rst_frm = 1;
				clr_rdy = 1;
				nxt_state = 3'b100;
			end
		end
		3'b001:begin
			nxt_state = 3'b001;
			tx_byte = 0;
			if(tx_done)begin
				nxt_state = 3'b010;
				tx_byte = 0;
				trmt = 1;
			end
		end
		3'b010:begin
			nxt_state = 3'b010;
			if(tx_done)
				nxt_state = 3'b000;
		end

		
		3'b100:begin
			nxt_state = 3'b100;
			if(rdy)begin
				nxt_state = 3'b101;
				byte2 = 1;
				clr_rdy = 1;
			end
		end
		3'b101:begin
			nxt_state = 3'b101;
			if(rdy)begin
				byte3 = 1;
				set_frm = 1;
				clr_rdy = 1;
				nxt_state = 3'b000;
			end
		end
		endcase
end


endmodule
